#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

static const std::string g_PipeFile = "fifo.ipc";
#define MODE 0666

int main()
{
    // 创建命名管道
    if(mkfifo(g_PipeFile.c_str(), MODE) < 0)
    {
        printf("Create pipe fail, %d:%s\n", errno, strerror(errno));
        exit(1);
    }

    // 以写的方式打开命名管道文件
    int fd = open(g_PipeFile.c_str(), O_WRONLY);
    if(fd < 0)
    {
        printf("Open fail, %d:%s\n", errno, strerror(errno));
        exit(2);
    }

    // 开始发送数据
    std::string message;

    while(true)
    {
        std::cout << "Pease input the message: > " << std::flush;
        std::getline(std::cin, message);

        if(message == "quit")
        {
            printf("Client quit!\n");
            break;
        }

        // 开始发送数据
        ssize_t n = write(fd, message.c_str(), message.size());
        
        switch(n)
        {
        case 0:
            printf("Nothing was written!\n");
            break;
        case -1:
            printf("Write error!\n");
            break;
        default:
            printf("Send meaasge success!\n");
            break;
        }
    }

    // 关闭文件描述符，删除命名管道文件
    close(fd);
    unlink(g_PipeFile.c_str());

    return 0;
}